package com.example.esredisrabbitmqdemo.conf;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;

/**
 * 创建延时队列，死信交换机，工作队列
 */
@Configuration
public class DelayQueueConfig implements Ordered {
    //接受消息的队列名
    public final static String DELAY_QUEUE_PER_QUEUE_TTL_NAME = "delay_queue_per_queue_ttl";
    //处理过期消息的队列名
    public final static String DELAY_PROCESS_QUEUE_NAME = "delay_process_queue";
    //接受过期消息的交换机
    public final static String DELAY_EXCHANGE_NAME = "delay_exchange";
    //过期时间 也可以成为 延时时间
    public final static int QUEUE_EXPIRATION = 4000;

    //创建接受消息的队列 并给每个消息设置过期时间
    @Bean
    Queue delayQueuePerQueueTTL() {
        return QueueBuilder.durable(DELAY_QUEUE_PER_QUEUE_TTL_NAME)
                .withArgument("x-dead-letter-exchange", DELAY_EXCHANGE_NAME) // DLX 配置死信交换机
                .withArgument("x-dead-letter-routing-key", DELAY_PROCESS_QUEUE_NAME) // dead letter携带的routing key 配置死信交换机转发的目标队列
//                .withArgument("x-message-ttl", QUEUE_EXPIRATION) // 设置队列消息的过期时间  如果需要自定义时间 这行代码注释掉
                .build();
    }

    //创建实际处理消息的队列
    @Bean
    Queue delayProcessQueue() {
        return QueueBuilder.durable(DELAY_PROCESS_QUEUE_NAME)
                .build();
    }

    //创建交换机
    @Bean
    DirectExchange delayExchange() {
        return new DirectExchange(DELAY_EXCHANGE_NAME);
    }

    //完成处理队列和交换机的绑定
    @Bean
    Binding dlxBinding(Queue delayProcessQueue, DirectExchange delayExchange) {
        return BindingBuilder.bind(delayProcessQueue)
                .to(delayExchange)
                .with(DELAY_PROCESS_QUEUE_NAME);
    }

    @Override
    public int getOrder() {
        return -100;
    }
}


